﻿using LayuiMvc.DataEntity;
using LayuiMvc.DataEntity.DataEntity;
using LayuiMvcUtil.Exception;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LayuiMvc.Logic.Community
{
    public class PostReplyService
    {
        #region 帖子回复管理==帖子回复
        /// <summary>
        /// 帖子回复
        /// </summary>
        /// <param name="saveEntity">帖子回复实体类</param>
        /// <returns></returns>
        public async Task<int> PostReplySaveAsync(PostReplyEntity saveEntity)
        {
            using(EFContext db=new EFContext())
            {
                db.Entry(saveEntity).State = EntityState.Added;
                int affectLineCount = await db.SaveChangesAsync();
                if (affectLineCount==0)
                {
                    throw new CustomException("评论保存失败");

                }
                return saveEntity.ReplyId;
            }
        }
        #endregion

        #region 帖子回复管理==帖子回复采纳
        /// <summary>
        /// 帖子回复采纳
        /// </summary>
        /// <param name="postId">帖子ID</param>
        /// <param name="replyId">评论ID</param>
        /// <returns></returns>
        public async Task PostReplyAcceptAsync(int postId,int replyId)
        {
            using(EFContext db=new EFContext())
            {
                var query = await db.Posts.Include(m => m.Replys).FirstOrDefaultAsync(m => m.PostId == postId);
                query.IsEnd = true;
                query.Replys.FirstOrDefault(m => m.ReplyId == replyId).IsAccept = true;
                db.Entry(query).State = EntityState.Modified;
                int affectLineCount = await db.SaveChangesAsync();
                if (affectLineCount==0)
                {
                    throw new CustomException("数据保存失败");
                }
            }
        }
        #endregion

        #region 帖子回复管理==评论删除

        public async Task ReplyDeleteAsync(int postId,int replyId)
        {
            using(EFContext db=new EFContext())
            {
                var query =await db.PostReplys.FirstOrDefaultAsync(m => m.ReplyId == replyId && m.PostId == postId);
                db.Entry(query).State = EntityState.Deleted;
                int affectLineCount = await db.SaveChangesAsync();

                if (affectLineCount==0)
                {
                    throw new CustomException("帖子回复删除失败");
                }
            }
        }
        #endregion
    }
}
